//
//  SearchViewController.m
//  aMoment
//
//  Created by dllo on 15/10/15.
//  Copyright © 2015年 LuckyHan. All rights reserved.
//

#import "SearchViewController.h"
#import "AllHeaderFiles.h"

#define HotURLString @"http://api2.pianke.me/search/hotlist"
#define SuggestURLString @"http://api2.pianke.me/search/suggest"
#define IndexURLString @"http://api2.pianke.me/search/index"
#define HotBodyString @"client=2"

@interface SearchViewController ()<UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate>
@property(nonatomic, retain)UITableView *tableView;
@property(nonatomic, retain)UISearchBar *searchBar;
@property(nonatomic, retain)NSMutableArray *dataSourceArray;
@property(nonatomic, retain)NSString *urlString;
@property(nonatomic, retain)NSString *bodyString;
@property(nonatomic, assign)NSInteger flag;
@property(nonatomic, retain)NSString *keyword;
@end

@implementation SearchViewController

- (void)dealloc
{
    [_tableView release];
    [_searchBar release];
    [_dataSourceArray release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"搜索";
//    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-back@2x"] style:UIBarButtonItemStylePlain target:self action:@selector(backToMenu)];//左侧按钮
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(backToMenu)];//左侧按钮
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(backKeyboard)];//右侧按钮
    
    self.urlString = HotURLString;
    self.bodyString = HotBodyString;
    
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 150, 50)];
    _searchBar.placeholder = @"搜索";
    _searchBar.delegate = self;
    _searchBar.returnKeyType = UIReturnKeyDone;
    self.navigationItem.titleView = _searchBar;
    [_searchBar release];
    
    [self getData];
}

#pragma mark searchBar协议方法
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if ([searchText isEqualToString:@""]) {
        _urlString = HotURLString;
        _bodyString = HotBodyString;
        _tableView.tableHeaderView = [self createHeaderView];
        _flag = 0;
    }
    else {
        self.keyword = searchText;
        _urlString = SuggestURLString;
        _bodyString = [NSString stringWithFormat:@"client=2&keyword=%@", searchText];
        _tableView.tableHeaderView = nil;
        _flag = 1;
    }
    [self getData];
}

#pragma mark 返回菜单
- (void)backToMenu
{
    [self.navigationController popViewControllerAnimated:YES];
    [(DDMenuController *)self.view.window.rootViewController showLeftController:YES];
}

#pragma mark 获取数据
- (void)getData
{
    self.dataSourceArray = [NSMutableArray array];
    [NetworkRequest getDataWithURLString:_urlString BodyString:_bodyString DataBlock:^(id data) {
        if (_flag == 0) {
            for (NSDictionary *dict in [(NSDictionary *)data objectForKey:@"data"]) {
                RecommendSearch *recommend = [[RecommendSearch alloc] init];
                [recommend setValuesForKeysWithDictionary:dict];
                [_dataSourceArray addObject:recommend];
            }
        }
        if (_flag == 1) {
            self.dataSourceArray = [NSMutableArray arrayWithArray:[(NSDictionary *)data objectForKey:@"data"]];
        }
//        if (_flag == 2) {
//            NSLog(@"%@", data);
//        }
        [_tableView reloadData];
        
        //搜索无结果
        if (_dataSourceArray.count == 0) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"没有搜索到结果" preferredStyle:UIAlertControllerStyleAlert];
            [self presentViewController:alert animated:YES completion:^{
                [alert dismissViewControllerAnimated:YES completion:nil];
            }];
        }
    }];
}

- (void)loadView
{
    [super loadView];
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64) style:UITableViewStylePlain];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.tableFooterView = [[UIView alloc] init];
    _tableView.tableHeaderView = [self createHeaderView];
    [self.view addSubview:_tableView];
    [_tableView release];
}

#pragma mark 创建headerView
- (UILabel *)createHeaderView
{
    UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44)];
    headerLabel.text = @"他们正在推荐";
    headerLabel.textAlignment = NSTextAlignmentCenter;
    headerLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:17];
    return headerLabel;
}

#pragma mark cell个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataSourceArray.count;
}

#pragma mark cell样式
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    if (_flag == 0) {
        cell.textLabel.text = [_dataSourceArray[indexPath.row] title];
    }
    if (_flag == 1) {
//        cell.textLabel.text = [_dataSourceArray[indexPath.row] objectForKey:@"name"];
        cell.textLabel.attributedText = [self keywordHighlight:[_dataSourceArray[indexPath.row] objectForKey:@"name"]];
    }
    return cell;
}

#pragma mark 关键字高亮
- (NSMutableAttributedString *)keywordHighlight:(NSString *)title
{
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:title];
    NSRange range = [title rangeOfString:_keyword];
    [attributedString setAttributes:[NSMutableDictionary dictionaryWithObjectsAndKeys:[UIColor redColor], NSForegroundColorAttributeName, nil] range:range];
    return attributedString;
}

#pragma mark cell点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [_searchBar resignFirstResponder];
    RecommendSearch *recommend = [_dataSourceArray objectAtIndex:indexPath.row];
    if (_flag == 0) {
        //判断是哪种详情页
        if ([[NSString stringWithFormat:@"%@", recommend.type] isEqualToString:@"24"]) {
            StoreDetailsViewController *detailsVC = [[StoreDetailsViewController alloc] init];
            [self.navigationController pushViewController:detailsVC animated:YES];
            detailsVC.contentID = recommend.contentid;
            [detailsVC release];
        }
        if ([[NSString stringWithFormat:@"%@", recommend.type] isEqualToString:@"1"]) {
            HomeDetailsViewController *detailsVC = [[HomeDetailsViewController alloc] init];
            [self.navigationController pushViewController:detailsVC animated:YES];
            detailsVC.contentId = recommend.contentid;
            [detailsVC release];
        }
        if ([[NSString stringWithFormat:@"%@", recommend.type] isEqualToString:@"17"]) {
            RadioDetailsInfoViewController *detailsVC = [[RadioDetailsInfoViewController alloc] init];
            [self.navigationController pushViewController:detailsVC animated:YES];
            detailsVC.tingId = [recommend.playInfo objectForKey:@"tingid"];
            [detailsVC release];
        }
    }
    if (_flag == 1) {
        _urlString = IndexURLString;
        _bodyString = [NSString stringWithFormat:@"client=2&keyword=%@", [self.dataSourceArray[indexPath.row] objectForKey:@"name"]];
//        _flag = 2;
        [_searchBar resignFirstResponder];
//        [self getData];
        
        //跳转
        SearchDetailsViewController *detailsVC = [[SearchDetailsViewController alloc] init];
        [self.navigationController pushViewController:detailsVC animated:YES];
        detailsVC.prevBodyString = _bodyString;
        [detailsVC release];
    }
}

#pragma mark 回收键盘
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [_searchBar resignFirstResponder];
}
- (void)backKeyboard
{
    [_searchBar resignFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
